<?php

namespace App\Http\Controllers\Admin;

use App\Category;
use App\Models;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
	function add()
	{
		$arr = Category::getTree();
		//获取所有的模型
		$modelCols = Models::get();
		return view('admin.category.add', ['modelCols' => $modelCols, 'arr' => $arr]);
	}
	function doadd(Request $request)
	{
		$arr = $request->all();
		//数据的合法性验证 名称唯一   
		//英文名称 唯一且内容有英文字母和数字组成不能有空格
		$this->validate($request, [
			'cname' => ['required', 'unique:category'],
			'enname' => ['required', 'unique:category', 'regex:/^[a-z][a-z0-9]*$/i']
		], [
			'cname.required' => '请填写栏目名称',
			'cname.unique' => '栏目名称已经存在',
			'enname.required' => '请填写英文名称',
			'enname.unique' => '英文栏目名称已经存在',
			'enname.regex' => "英文栏目名称格式错误"
		]);
		$re = Category::create($arr);
		if ($re) {
			return redirect('admin/category/add')->with('message', "添加成功");
		} else {
			return redirect('admin/category/add')->with('message', "添加失败");
		}
	}
	function index()
	{
		$arr = Category::getTree();
		return view('admin.category.index', ['arr' => $arr]);
	}
	function edit($id)
	{
		$arr = Category::getTree();
		$modelCols = Models::get();
		$ob = Category::where('id', $id)->first();
		return view('admin.category.edit', ['ob' => $ob, 'modelCols' => $modelCols, 'arr' => $arr]);
	}
	function doedit(Request $request)
	{
		$arr = $request->all();
		$id = $arr['id'];
		unset($arr['id']);
		unset($arr['_token']);
		$re = Category::where('id', $id)->update($arr);
		$message = $re ? "修改成功" : "修改失败";
		return redirect('admin/category/index')->with('message', $message);
	}
	function del($id)
	{
		//不能删除有子栏目的栏目
		$num = Category::where('pid', $id)->count();
		if ($num > 0) {
			return redirect()->back()->with('message', "请先删除此栏目的子栏目");
		} else {
			$re = Category::where('id', $id)->delete();
			$message = $re ? "删除成功" : "删除失败";
			return redirect()->back()->with('message', $message);
		}
	}
}
